package com.baidu.ueditor.upload;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;
import com.ifast.common.utils.GenUtils;
import com.ifast.common.utils.alioss.UploadResult;
import com.ifast.common.utils.alioss.UploadUtils;
import com.xiaoleilu.hutool.util.CollectionUtil;

import lombok.Cleanup;

public class BinaryUploader {

	public static final State save(HttpServletRequest request, Map<String, Object> conf) {
		if (!ServletFileUpload.isMultipartContent(request)) {
			return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
		}
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile multipartFile = multipartRequest.getFile(conf.get("fieldName").toString());
			if (multipartFile == null) {
				return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
			}

			String savePath = (String) conf.get("savePath");
			// String originFileName = fileStream.getName();
			String originFileName = multipartFile.getOriginalFilename();
			String suffix = FileType.getSuffixByFilename(originFileName);

			originFileName = originFileName.substring(0, originFileName.length() - suffix.length());
			savePath = savePath + suffix;

			long maxSize = ((Long) conf.get("maxSize")).longValue();
			if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
				return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
			}

			savePath = PathFormat.parse(savePath, originFileName);

			String basePath = (String) conf.get("basePath");
			String physicalPath = basePath + savePath;

			@Cleanup InputStream is = multipartFile.getInputStream();
			Integer filelength = is.available();
			// 判断文件大小
			if (filelength > maxSize) {
				return new BaseState(false, AppInfo.MAX_SIZE);
			}
			Configuration confP = GenUtils.getConfig();
			// 创建文件夹
			String path = confP.getString("file") + physicalPath;
			File file = new File(path);
			File fileParent = file.getParentFile();
			if (!fileParent.exists()) {
				fileParent.mkdirs();
			}
			file.createNewFile();

			@Cleanup FileOutputStream fos = new FileOutputStream(path); 
			@Cleanup BufferedInputStream bis = new BufferedInputStream(is);
			
			byte[] buff = new byte[128];
			int count = -1;

			while ((count = bis.read(buff)) != -1) {

				fos.write(buff, 0, count);

			} 

			State storageState = new BaseState(true); 
			storageState.putInfo("url", confP.getString("path") + "common/" + physicalPath);
			storageState.putInfo("type", suffix);
			storageState.putInfo("original", originFileName + suffix);
			return storageState;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}

	private static boolean validType(String type, String[] allowTypes) {
		return Arrays.asList(allowTypes).contains(type);
	}

	public static final State saveAlioss(HttpServletRequest request, Map<String, Object> conf) {
		if (!ServletFileUpload.isMultipartContent(request))
			return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
		
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile multipartFile = multipartRequest.getFile(conf.get("fieldName").toString());
			if (multipartFile == null)
				return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
			
			String originFileName = multipartFile.getOriginalFilename();
			String suffix = FileType.getSuffixByFilename(originFileName);
			originFileName = originFileName.substring(0, originFileName.length() - suffix.length());
			//检测文件类型
			long maxSize = ((Long) conf.get("maxSize")).longValue();
			
			if (!validType(suffix, (String[]) conf.get("allowFiles")))
				return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
		 
			@Cleanup
			InputStream is = multipartFile.getInputStream();
			Integer filelength = is.available();
			// 判断文件大小
			if (filelength > maxSize)
				return new BaseState(false, AppInfo.MAX_SIZE);
			//上传阿里云
			UploadResult  result = UploadUtils.uploadOssPic(request);
			if(CollectionUtil.isEmpty(result.getFileURLs()))
				return new BaseState(false, AppInfo.CONFIG_ERROR);
			
			State storageState = new BaseState(true); 
			storageState.putInfo("url",result.getFileURLs().get(0));
			storageState.putInfo("type", suffix);
			storageState.putInfo("original", originFileName + suffix);
			return storageState;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}
	/*
	 * public static final State save(HttpServletRequest request, Map<String,
	 * Object> conf) { FileItemStream fileStream = null; boolean isAjaxUpload =
	 * request.getHeader( "X_Requested_With" ) != null;
	 * 
	 * if (!ServletFileUpload.isMultipartContent(request)) { return new
	 * BaseState(false, AppInfo.NOT_MULTIPART_CONTENT); }
	 * 
	 * ServletFileUpload upload = new ServletFileUpload( new
	 * DiskFileItemFactory());
	 * 
	 * if ( isAjaxUpload ) { upload.setHeaderEncoding( "UTF-8" ); }
	 * 
	 * try { FileItemIterator iterator = upload.getItemIterator(request);
	 * 
	 * while (iterator.hasNext()) { fileStream = iterator.next();
	 * 
	 * if (!fileStream.isFormField()) break; fileStream = null; }
	 * 
	 * if (fileStream == null) { return new BaseState(false,
	 * AppInfo.NOTFOUND_UPLOAD_DATA); }
	 * 
	 * String savePath = (String) conf.get("savePath"); String originFileName =
	 * fileStream.getName(); String suffix =
	 * FileType.getSuffixByFilename(originFileName);
	 * 
	 * originFileName = originFileName.substring(0, originFileName.length() -
	 * suffix.length()); savePath = savePath + suffix;
	 * 
	 * long maxSize = ((Long) conf.get("maxSize")).longValue();
	 * 
	 * if (!validType(suffix, (String[]) conf.get("allowFiles"))) { return new
	 * BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE); }
	 * 
	 * savePath = PathFormat.parse(savePath, originFileName);
	 * 
	 * String physicalPath = (String) conf.get("rootPath") + savePath;
	 * 
	 * InputStream is = fileStream.openStream(); State storageState =
	 * StorageManager.saveFileByInputStream(is, physicalPath, maxSize);
	 * is.close();
	 * 
	 * if (storageState.isSuccess()) { storageState.putInfo("url",
	 * PathFormat.format(savePath)); storageState.putInfo("type", suffix);
	 * storageState.putInfo("original", originFileName + suffix); }
	 * 
	 * return storageState; } catch (FileUploadException e) { return new
	 * BaseState(false, AppInfo.PARSE_REQUEST_ERROR); } catch (IOException e) {
	 * } return new BaseState(false, AppInfo.IO_ERROR); }
	 * 
	 * private static boolean validType(String type, String[] allowTypes) {
	 * List<String> list = Arrays.asList(allowTypes);
	 * 
	 * return list.contains(type); }
	 */
}
